package income

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"
)

const dbName = "income"

type IncomeDbModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
}

func (this *IncomeDbModel) FindOne(filter Income, opts *options.FindOneOptions) *mongo.SingleResult {
	filterBsonByte, err := this.CommonFunc.BsonMarshal(filter)
	if err != nil {
		panic(err)
	}
	return this.MDB.Collection(dbName).FindOne(context.TODO(), filterBsonByte, opts)
}

func (this *IncomeDbModel) Find(filter bson.D, opts *options.FindOptions) *mongo.Cursor {
	result, err := this.MDB.Collection(dbName).Find(context.TODO(), filter, opts)
	if err == mongo.ErrNoDocuments {
		return nil
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *IncomeDbModel) CountDocuments(filter bson.D, opts *options.CountOptions) int64 {
	result, err := this.MDB.Collection(dbName).CountDocuments(context.TODO(), filter, opts)
	if err == mongo.ErrNoDocuments {
		return 0
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *IncomeDbModel) Upsert(update Income) {
	filterBsonD, err := this.CommonFunc.StructToBsonD(Income{
		MinerId: update.MinerId,
		Time:    update.Time,
	})
	if err != nil {
		panic(err)
	}
	updateBsonD, err := this.CommonFunc.StructToBsonD(update)
	if err != nil {
		panic(err)
	}
	opts := options.Update().SetUpsert(true)
	updateSet := bson.D{{"$set", updateBsonD}}
	_, err = this.MDB.Collection(dbName).UpdateOne(context.TODO(), filterBsonD, updateSet, opts)
	if err != nil {
		panic(err)
	}
}

func (this *IncomeDbModel) DeleteOne(filter Income) {
	filterBsonD, err := this.CommonFunc.StructToBsonD(filter)
	this.Log.Debug("%+v", filterBsonD)
	opts := options.Delete()
	_, err = this.MDB.Collection(dbName).DeleteOne(context.TODO(), filterBsonD, opts)
	if err != nil {
		panic(err)
	}
}
